const userModel = require('../models/users');
const chatsModel = require('../models/chats');

async function saveChatContentService(params) {
  const {sendId, receiveId, content} = params;
  if (!sendId || !receiveId || !content) {
    return {
      status: 400,
      msg: '发送者 id 或接受者 id 或发送内容不存在'
    }
  }

  const sendUser = await userModel.findById(sendId);
  if (!sendUser) {
    return {
      status: 400,
      msg: '发送用户不存在'
    }
  }

  const receiveUser = await userModel.findById(receiveId);
  if (!receiveUser) {
    return {
      status: 400,
      msg: '接收用户不存在'
    }
  }

  let unionId = [sendId, receiveId].sort().join('_');

  const result = await chatsModel.create({
    unionId,
    sendId,
    receiveId,
    content,
    read: false
  });
  return {
    msg: null,
    data: result
  }
}


module.exports = {
  saveChatContentService
};
